package com.jxw.cloudpen.web.microsoft.concurrency;

import com.alibaba.fastjson.JSONObject;
import com.jxw.cloudpen.web.microsoft.stremspeed.StreamData;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.handshake.ServerHandshake;

import javax.sound.sampled.TargetDataLine;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

@Slf4j
public class WebSocketClient2 extends org.java_websocket.client.WebSocketClient {

    public WebSocketClient2(URI serverUri) {
        super(serverUri);
    }

    @Override
    public void onOpen(ServerHandshake handshakedata) {
        System.out.println("Connected");
//        this.send("Hello Server!"); // 发送消息到服务器
//        for(;;){
//            this.send(ByteObjUtil.objToBytes("aaaa"));
//            this.send("aaaa");
//            try {
//                Thread.sleep(3000);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//        }
        StreamData request = new StreamData();
        request.setType(1);
        try {
            byte[] pcmData = readPcmFile("D:\\test.pcm");
            request.setData(pcmData);
            this.send(JSONObject.toJSONString(request));
        } catch (IOException e) {
            e.printStackTrace();
        }

//        try {
//            executeMusic();
//        } catch (LineUnavailableException e) {
//
//        }

    }

    public static byte[] readPcmFile(String filePath) throws IOException {
        File file = new File(filePath);
        byte[] buffer = new byte[(int) file.length()];

        try (FileInputStream fis = new FileInputStream(file)) {
            int bytesRead = fis.read(buffer);
            if (bytesRead != buffer.length) {
                throw new IOException("Could not read the entire PCM file. Only read " + bytesRead + " bytes.");
            }
        }
        return buffer;
    }





    private static TargetDataLine targetDataLine;

    private static volatile BlockingQueue<byte[]> sharedQueue = new LinkedBlockingQueue<byte[]>();

    @Override
    public void onMessage(String message) {
//        System.out.println("Received: " + message);

//        log.info("onMessage is excute");
        JSONObject jsonObject = JSONObject.parseObject(message);
        jsonObject.getString("clientId");

        StreamData request = new StreamData();
        request.setType(1);
        try {
            byte[] pcmData = readPcmFile("D:\\test.pcm");
            request.setData(pcmData);
            this.send(JSONObject.toJSONString(request));
        } catch (IOException e) {
            e.printStackTrace();
        }
//        try {
        //主动挂断
//            executorService.submit(()-> {
//                try {
//                    try {
//                        Thread.sleep(30000L);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
//                    StreamData result = new StreamData();
//                    result.setClientId("f544f5209e7d4f59a82ba3a780736faf");
//                    result.setType(3);
//                    isStop = true;
//                    this.send(JSONObject.toJSONString(result));
//                } catch (Exception e) {
//                    System.out.println("Exception caught: " + e);
//                }
//            });


        //切换语言
//        executorService.submit(() -> {
//            try {
//                try {
//                    Thread.sleep(30000L);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//                StreamData result = new StreamData();
//                result.setClientId("f544f5209e7d4f59a82ba3a780736faf");
//                result.setType(4);
//                result.setLanguageCode("en-US");
//                this.send(JSONObject.toJSONString(result));
//            } catch (Exception e) {
//                System.out.println("Exception caught: " + e);
//            }
//        });
//
//
    }

    @Override
    public void onMessage(ByteBuffer bytes) {
        System.out.println("Received: " + bytes);
    }

    @Override
    public void onClose(int code, String reason, boolean remote) {
        System.out.println("Disconnected");
    }

    @Override
    public void onError(Exception ex) {
        System.err.println("Error: " + ex.getMessage());
    }

    public static void main(String[] args) throws URISyntaxException {
//        String url = "wss://gwsdb-sgp-test.xuexizhiwang.com/stream-speech";
        String url = "ws://localhost:6601/stream-test";
//        String url = "ws://172.26.28.68:6601/stream-speech";


//        String url = "ws://localhost:6601/websocket";
        WebSocketClient2 client = new WebSocketClient2(new URI(url)); // 替换为你的WebSocket服务器地址和端点
        client.connect();
    }
}
